package com.sc.ktapplication.common.util.RsaUtils;

import android.annotation.SuppressLint;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@SuppressLint("DefaultLocale")
public final class MD5Utils {
	private static final String LOG_TAG = "MD5";
	private static final String ALGORITHM = "md5";

	private static char sHexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

	private static MessageDigest sDigest;

	static {
		try {
			sDigest = MessageDigest.getInstance(ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			Log.e(LOG_TAG, "Get MD5 Digest failed.");
			try {
				throw new Exception(ALGORITHM, e);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	private MD5Utils() {
	}

	
	final public static String encode(String source) {
		byte[] btyes;
		try {
			btyes = source.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			btyes = source.getBytes();
		}
		byte[] encodedBytes = sDigest.digest(btyes);

		return hexString(encodedBytes);
	}
	
	final public static String encode(byte[] btyes) {
		byte[] encodedBytes = sDigest.digest(btyes);
		return hexString(encodedBytes);
	}
	
	public static String hexString(byte[] source) {
		if (source == null || source.length <= 0) {
			return "";
		}

		final int size = source.length;
		final char str[] = new char[size * 2];
		int index = 0;
		byte b;
		for (int i = 0; i < size; i++) {
			b = source[i];
			str[index++] = sHexDigits[b >>> 4 & 0xf];
			str[index++] = sHexDigits[b & 0xf];
		}
		return new String(str);
	}

	
	
	public static String getMD5(String str, String encoding) throws Exception {
	    MessageDigest md = MessageDigest.getInstance(ALGORITHM);
	    md.update(str.getBytes(encoding));
	    byte[] result = md.digest();
	    StringBuffer sb = new StringBuffer(32);
	    for (int i = 0; i < result.length; i++) {
	        int val = result[i] & 0xff;
	        if (val < 0xf) {
	            sb.append("0");
	        }
	        sb.append(Integer.toHexString(val));
	    }
	    return sb.toString().toLowerCase();
	}


	public static String encoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md5= MessageDigest.getInstance(ALGORITHM);
		BASE64Encoder base64en = new BASE64Encoder();
		String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
		return newstr;
	}

//	public static void main(String[] args) {
//		// MD5Utils ("") = d41d8cd98f00b204e9800998ecf8427e
//		System.out.println(MD5Utils.encode(""));
//		// MD5Utils ("a") = 0cc175b9c0f1b6a831c399e269772661
//		System.out.println(MD5Utils.encode("a"));
//		// MD5Utils ("abc") = 900150983cd24fb0d6963f7d28e17f72
//		System.out.println(MD5Utils.encode("abc"));
//	}


}
